<script setup>
import {ref, onMounted} from 'vue';
import {Plus,Search} from "@element-plus/icons-vue";
import {getUserPage, queryUser, banUser, unbanUser} from '@/apis/user.js';
import editUser from "@/views/user/editUser.vue";

const formData = ref({
  username: undefined,
  nickname: undefined,
  phone: undefined,
  email: undefined,
  status: undefined,
  findUsers: undefined,
});

const rules = ref({
  username: [],
  nickname: [],
  phone: [],
  email: [],
  status: [],
});

const total = ref(0);
const current = ref(1);
const size = ref(10);
const drawer = ref(false);
const userMsg = ref({});

const statusOptions = ref([
  {label: '禁用', value: 0},
  {label: '正常', value: 1},
]);

const tableData = ref([]);

const init = async () => {
  const params = {
    current: current.value,
    pageSize: size.value,
  };
  await getUserPage(params).then((res) => {
    if (res.data.code === 1) {
      tableData.value = res.data.data.records;
      total.value = Number(res.data.data.total);
    } else {
      // Handle error
      console.error(res.data.msg || '操作失败');
    }
  }).catch((err) => {
    // Handle error
    console.error('请求出错了：' + err);
  });
};

const userQuery = () => {
  current.value = 1;
  init();
};

const findUserList = () => {
  const params = {
    username: formData.value.username !== null ? formData.value.username : '',
    nickname: formData.value.nickname !== null ? formData.value.nickname : '',
    phone: formData.value.phone !== null ? formData.value.phone : '',
    email: formData.value.email !== null ? formData.value.email : '',
    status: formData.value.status !== null ? formData.value.status : '',
  };

  queryUser(params).then((res) => {
    if (res.data.code === 1) {
      total.value = res.data.data.total;
      tableData.value = res.data.data.records;
    } else {
      // Handle error
      ElMessage.error(res.data.msg || '查询失败');
    }
  }).catch((err) => {
    // Handle error
    ElMessage.error('请求出错了：' + res.data.msg);
  });
};

const banUserById = (id) => {
  ElMessageBox.confirm('此操作将封禁该用户, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    banUser(id).then((res) => {
      if (res.data.code === 1) {
        ElMessage.success('封禁成功');
        userQuery();
      } else {
        // Handle error
        ElMessage.error(res.msg || '封禁失败');
      }
    }).catch((err) => {
      // Handle error
      ElMessage.error('请求出错了：' + err);
    });
  });
};

const unbanUserById = (id) => {
  ElMessageBox.confirm('此操作将解封该用户, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    unbanUser(id).then((res) => {
      if (res.data.code === 1) {
        ElMessage.success('解封成功');
        userQuery();
      } else {
        // Handle error
        ElMessage.error(res.msg || '封禁失败');
      }
    }).catch((err) => {
      // Handle error
      ElMessage.error('请求出错了：' + err);
    });
  });
};

const closeDrawer = () => {
  drawer.value = false;
}

const handleClose = () => {
// 确认弹窗
  if (confirm('确认退出不保存？')) {
    closeDrawer()
  }
}

const openDrawer = (row) => {
  drawer.value = true;
  userMsg.value = row;
};

const userSizeChange = (val) => {
  size.value = val;
  init();
};

const currentChange = (val) => {
  current.value = val;
  init();
};

onMounted(() => {
  init();
});

</script>

<template>
  <div id="user-app" class="dashboard-container">
    <div class="container">
      <div class="tableBar">
        <el-form ref="findUser" :model="formData" :rules="rules" label-position="left" label-width="px">
          <el-row :gutter="20" align="top" justify="start" type="flex">
            <el-col :span="7">
              <el-form-item label="用户名：" label-width="71px" prop="username">
                <el-input v-model="formData.username" :style="{width: '100%'}" clearable
                          placeholder="请输入用户名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="昵称：" label-width="56px" prop="nickname">
                <el-input v-model="formData.nickname" :style="{width: '100%'}" clearable
                          placeholder="请输入昵称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="手机号码：" label-width="82px" prop="phone">
                <el-input v-model="formData.phone" :style="{width: '100%'}" clearable
                          placeholder="请输入手机号码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="邮箱：" label-width="56px" prop="email">
                <el-input v-model="formData.email" :style="{width: '100%'}" clearable
                          placeholder="请输入邮箱"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="用户状态：" label-width="84px" prop="status">
                <el-select v-model="formData.status" :style="{width: '100%'}" clearable placeholder="请选择用户状态">
                  <el-option v-for="(item, index) in statusOptions" :key="index" :disabled="item.disabled" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label-width="0" prop="findUsers">
                <el-button :icon="Search" type="primary" @click="findUserList">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table :cell-style="{padding:'16px 0'}" :data="tableData" class="tableBox" stripe>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="昵称" prop="nickname"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="手机号码" prop="phone"></el-table-column>
        <el-table-column label="用户状态">
          <template #default="scope">{{ scope.row.status === 0 ? '禁用' : '正常' }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="160">
          <template #default="scope">
            <el-button class="blueBug" size="small" type="text" @click="openDrawer(scope.row)">修改</el-button>
            <el-button v-if="scope.row.status===1" class="delBut non" size="small" type="text"
                       @click="banUserById(scope.row.id)">封禁
            </el-button>
            <el-button v-else class="delBut non" size="small" type="text" @click="unbanUserById(scope.row.id)">解封
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="current" :total=total background class="pageList" layout="prev, pager, next"
                     @current-change="currentChange"/>
    </div>
    <el-drawer
        v-model=drawer
        :before-close="handleClose"
        :destroy-on-close=true
        :direction="trl"
        size="50%"
        title="I am the title"
    >
      <edit-user :userMsg="userMsg" @closeDrawer='closeDrawer'></edit-user>
    </el-drawer>
  </div>
</template>

<style scoped>
@import "@/styles/page.css";

.el-table__cell {
  padding: 16px 12px;
}

el-table-column {
  height: 50px;
}

.el-table .cell {
  box-sizing: border-box;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  padding: 16px 12px;
}
</style>